// import { CommonTable } from '@/pages/OrderModule/common/components/CommonTable';
import CommonTable from '@/components/CommonTable';
import { NumText } from '@/pages/OrderModule/common/components/CommonText';
import ResetStyle from '@/pages/OrderModule/common/components/ResetStyle';
import { Alert, Image, Tabs, message } from 'antd';
import { cloneDeep, findIndex } from 'lodash';
import { memo, useEffect, useState } from 'react';
import { getPackageDataOp } from '@/services/common';
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { formatZjfImg } from '@/utils/utils.jsx';

const { TabPane } = Tabs;

function GoodsList(props) {

    const { type } = props;

    const [data, setData] = useState([]);
    const [selectedRowKeys, setSelectRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);

    useEffect(()=>{
      getPackData();
    }, [])
    
    //获取包材数据
    const getPackData = async () => {
    const { success, data = {} } = await getPackageDataOp({ 
        type: type == 1 ? (window.APP_TITLE == '找家纺' ? 1 : 5) : (window.APP_TITLE == '找家纺' ? 2 : 6), 
        current: 1, 
        size: 1000 
    });
    if (success) {
        setData((data?.records || []).map(item=>{
            return ({
                ...item,
                orderGoodsType: type == 1 ? 'gifts' : 'package',
                goodsNum: item.goodsNum || 1
            })
        }));
    }
    }

    const columns = [
        {
            title: '序号',
            dataIndex: 'key',
            key: 'key',
            with: 80,
            render(text, record, index) {
                return index + 1;
            },
        },
        {
            title: '图片',
            dataIndex: 'image',
            key: 'image',
            with: 80,
            render(text, record) {
                return <Image src={formatZjfImg(record.goodsImage, record.storeId)} alt="logo" width={32} height={32} />;
            },
        },
        {
            title: `${type == 2 ? '包装名称' : '赠品名称'}`,
            dataIndex: 'goodsName',
            key: 'goodsName',
            width:160
        },
        {
            title: '商品编码',
            dataIndex: 'goodsId',
            key: 'goodsId',
        },
        {
            title: '款式编码',
            dataIndex: 'goodsCommonid',
            key: 'goodsCommonid',
        },
        {
            title: '价格',
            dataIndex: 'goodsPrice',
            key: 'goodsPrice',
            render(text) {
                return <NumText type="error" as="s1" pre="¥" num={text}/>;
            },
        },
        {
            title: '数量',
            dataIndex: 'goodsNum',
            key: 'goodsNum',
            render: (text, { goodsId }, index) => <CommonInputNumber size='small' value={text} onBlur={e => handleNumChange(e, index)} placeholder="请输入数量" controls={false} />
        },
    ];

      //更改商品数量
  const handleNumChange = (e, index) => {
    const val = Number(e.target.value);
    const reg = /^[1-9]\d*$/;
    if (val == data[index].goodsNum) {
      return;
    }
    const arr = cloneDeep(data);
    const seletedArr = cloneDeep(selectedRows);
    if (!val || (reg.test(val) && val < 100000)) {
      arr[index].goodsNum = val || null;
    } else {
      arr[index].goodsNum = 1;
      message.info("限输入1-100000的正整数");
    }
    const edItIndex = findIndex(seletedArr, ['goodsId', arr[index]?.goodsId]); //修改的数量是否勾选
    if(edItIndex > -1) {
        seletedArr[edItIndex].goodsNum = val;
    }
    setData(arr)
    setSelectedRows(seletedArr);
    props.onSelectionChange?.(seletedArr);
  };

    const tableProps = {
        data,
        columns,
        rowKey: 'goodsId',
        rowSelection: {
            selectedRowKeys,
            type: 'checkbox',
            onChange: (selectedRowKeys, selectedRows) => {
                setSelectRowKeys(selectedRowKeys)
                setSelectedRows(selectedRows);
                props.onSelectionChange?.(selectedRows);
            },
        }
    }

    return <CommonTable {...tableProps} />
    return (<CommonTable size="small" rowSelection={{
            type: 'checkbox',
            onChange: (selectedRowKeys, selectedRows) => {
                props.onChange(selectedRows);
            },
        }} bordered style={{ marginTop: 16 }} dataSource={data} columns={columns} pagination={false}/>);
}
function PackageAndGiveawayTabs(props) {
    // const { tabs = ['包装', '赠品'] } = props;
    // const [state, setState] = useState({ package: [], giveaway: [] });
    // useEffect(() => {
    //     props.onChange && props.onChange(state);
    // }, [state]);
    // const items = [];
    // if (tabs.includes('包装')) {
    //     items.push({
    //         key: '1',
    //         label: '包装',
    //         children: (<GoodsList onChange={(data) => {
    //                 setState({ ...state, package: data });
    //             }}/>),
    //     });
    // }
    // if (tabs.includes('赠品')) {
    //     items.push({
    //         key: '2',
    //         label: '赠品',
    //         children: (<GoodsList onChange={(data) => {
    //                 setState({ ...state, giveaway: data });
    //             }}/>),
    //     });
    // }
    // return <Tabs defaultActiveKey={'1'} items={items}/>;

    const [type, setType] = useState('2');

    // useEffect(()=>{
    //   props.changeTab?.(type);
    // }, [type])

    const commomProps = {
      type,
      onSelectionChange: props.onSelectionChange
    }

    return (<>
        <Alert message='这是代发仓订单需要的包装或赠品，自发单无需设置'  style={{marginBottom:"12px"}}/>
        <Tabs
            defaultActiveKey="0"
            onChange={(val) => {
                setType(val);
            }}
        >
            <TabPane tab="包装" key="2">
                <GoodsList {...commomProps} />
            </TabPane>
            <TabPane tab="赠品" key="1">
                <GoodsList {...commomProps} />
            </TabPane>
        </Tabs>
    </>)

}
export default memo(ResetStyle(PackageAndGiveawayTabs, { wrappers: ['rule-reset'] }));
